<?

function portal_start() {
	global $id,$portal_id,$domain,$row,$portal,$title;
	
	$bits = explode('.',$_SERVER['SERVER_NAME']);
	$domain = $bits[0];
	
	$portal = getRow("SELECT * FROM portal INNER JOIN user USING (user_id) WHERE domain = ".dbQuote($domain)." AND status_id = 1");
	
	if (empty($portal['portal_id'])) {
		if ($domain != 'portal')
			header("HTTP/1.0 404 Not Found");
		print "<html><head>";
		print "<title>Not found!</title>";
		print "</head><body>";
		print "<p>The page you are looking for is not available</p>";
		
		print "<p><a href=\"http://www.geographs.org/portals/?ref=$domain\">Try the Portal Homepage</a></p>";
	
		print "<hr>";
		include "portals.php";
	
	
		print "</body></html>";
		print str_repeat(" ",500);
		exit;
	}
	
	$portal_id = intval($portal['portal_id']);
	$title = $portal['title'];
	
	$portal['count'] = count_active($portal_id); 
	
	//for legacy reasons!
	$GLOBALS['row'] = $portal; 
	$id = $portal_id+0;
}


function he($in) {
	return  htmlentities($in);
}
function hec($in) {
	global $c;
	return  htmlentities($c[$in]);
}
function ehec($in) {
	echo hec($in);
}


function init_session()
{
	session_start();



}
	
	
function linktoself($params,$selflink= '') {
	$a = array();
	$b = explode('?',$_SERVER['REQUEST_URI']);
	if (isset($b[1])) 
		parse_str($b[1],$a);

	if (isset($params['value']) && isset($a[$params['name']])) {
		if ($params['value'] == 'null') {
			unset($a[$params['name']]);
		} else {
			$a[$params['name']] = $params['value'];
		}

	} else {
		foreach ($params as $key => $value)
			$a[$key] = $value;
	}

	if (!empty($params['delete'])) {
		if (is_array($params['delete'])) {
			foreach ($params['delete'] as $del) {
				unset($a[$del]);
			}
		} else {
			unset($a[$params['delete']]);
		}
		unset($a['delete']);
	} 
	if (empty($selflink)) {
		$selflink = $_SERVER['SCRIPT_NAME'];
	} 
	if ($selflink == '/index.php') {
		$selflink = '/';
	}

	return htmlentities($selflink.(count($a)?("?".http_build_query($a,'','&')):''));
}

function gGU($gridimage_id,$user_id,$size = 'small') {
	global $CONF;
	$hash = substr(md5(intval($gridimage_id).intval($user_id).$CONF['geograph_secret']), 0, 8);
	return getGeographUrl($gridimage_id,$hash,$size);
}

function gGUc(&$c,$size = 'small') {
	global $CONF;
	$hash = substr(md5(intval($c['gridimage_id']).intval($c['user_id']).$CONF['geograph_secret']), 0, 8);
	return getGeographUrl($c['gridimage_id'],$hash,$size);
}


function count_active($id) {

	$count = getOne("SELECT count FROM active_cache WHERE portal_id = $id AND updated > DATE_SUB(NOW(),INTERVAL 1 HOUR)");

	if ($count === 0 || $count > 0) {

	} else {
		$count = getOne("SELECT COUNT(*) FROM p2.gridimage{$id}_bi_view");

		queryExecute("REPLACE INTO active_cache SET portal_id = $id,count = $count");

	}
	return $count;
}


#########


function pagesString($currentPage,$numberOfPages,$postfix = '',$extrahtml ='') {
	static $r;
	if (!empty($r))
		return($r);

	if ($currentPage > 1) 
		$r .= "<a href=\"".linktoself(array('page'=>$currentPage-1))."$postfix\"$extrahtml>&lt; &lt; prev</a> ";
	$start = max(1,$currentPage-5);
	$endr = min($numberOfPages+1,$currentPage+8);

	if ($start > 1)
		$r .= "<a href=\"".linktoself(array('page'=>1))."$postfix\"$extrahtml>1</a> ... ";

	for($index = $start;$index<$endr;$index++) {
		if ($index == $currentPage) 
			$r .= "<b>$index</b> "; 
		else
			$r .= "<a href=\"".linktoself(array('page'=>$index))."$postfix\"$extrahtml>$index</a> ";
	}
	if ($endr < $numberOfPages+1) 
		$r .= "... ";

	if ($numberOfPages > $currentPage) 
		$r .= "<a href=\"".linktoself(array('page'=>$currentPage+1))."$postfix\"$extrahtml>next &gt;&gt;</a> ";

	#if ( $this->fullText && empty($_GET['legacy']) && $this->currentPage < $this->numberOfPages && $this->resultCount <= $this->maxResults ) 
	#	$r .= "<a href=\"/{$this->page}?i={$this->query_id}&amp;page=".($this->numberOfPages)."$postfix\"$extrahtml>last</a> ";
	return $r;
}
	
	
function GeographLinks(&$posterText,$thumbs = false) {
	global $imageCredits,$CONF,$global_thumb_count;
	//look for [[gridref_or_photoid]] and [[[gridref_or_photoid]]]
	if (preg_match_all('/\[\[(\[?)([a-z]+:)?(\w{0,3} ?\d+ ?\d*)(\]?)\]\]/',$posterText,$g_matches)) {
		$thumb_count = 0;
		foreach ($g_matches[3] as $g_i => $g_id) {
			$server = "www.geograph.org.uk";
			$ext = false;
			$prefix = '';
			if ($g_matches[2][$g_i] == 'de:') {
				$server = 'geo.hlipp.de';
				$ext = true;
				$prefix = 'de:';
			}
			//photo id?
			if (is_numeric($g_id)) {
				if ($global_thumb_count > $CONF['global_thumb_limit'] || $thumb_count > $CONF['post_thumb_limit']) {
					$posterText = preg_replace("/\[?\[\[$prefix$g_id\]\]\]?/","[[<a href=\"http://{$server}/photo/$g_id\">$prefix$g_id</a>]]",$posterText);
				} else {
					if (!isset($g_image)) {
						$g_image=new GridImage;
					}
					if ($ext) {
						$ok = $g_image->loadFromServer($server, $g_id);
					} else {
						$ok = $g_image->loadFromId($g_id);
					}
					if ($g_image->moderation_status == 'rejected') {
						if ($thumbs) {
							$posterText = str_replace("[[[$prefix$g_id]]]",'<img src="/photos/error120.jpg" width="120" height="90" alt="image no longer available"/>',$posterText);
						}
						$posterText = preg_replace("/\[{2,3}$prefix$g_id\]{2,3}/",'[image no longer available]',$posterText);
					} elseif ($ok) {
						$g_title=$g_image->grid_reference.' : '.htmlentities2($g_image->title);
						if ($g_matches[1][$g_i]) {
							if ($thumbs) {
								$g_title.=' by '.htmlentities($g_image->realname);
								$g_img = $g_image->getThumbnail(120,120,false,true);

								$posterText = str_replace("[[[$prefix$g_id]]]","<a href=\"http://{$server}/photo/$g_id\" target=\"_blank\" title=\"$g_title\">$g_img</a>",$posterText);
								if (isset($imageCredits[$g_image->realname])) {
									$imageCredits[$g_image->realname]++;
								} else {
									$imageCredits[$g_image->realname]=1;
								}
							} else {
								//we don't place thumbnails in non forum links
								$posterText = str_replace("[[[$prefix$g_id]]]","<a href=\"http://{$server}/photo/$g_id\">$g_title</a>",$posterText);
							}
						} else {
							$posterText = preg_replace("/(?<!\[)\[\[$prefix$g_id\]\]/","<a href=\"http://{$server}/photo/$g_id\">$g_title</a>",$posterText);
						}
					}
					$global_thumb_count++;
				}
				$thumb_count++;
			} else {
				//link to grid ref
				$posterText = str_replace("[[$prefix$g_id]]","<a href=\"http://{$server}/gridref/".str_replace(' ','+',$g_id)."\">$g_id</a>",$posterText);
			}
		}
	}
	
	$posterText = preg_replace('/(?<!["\'>F=])(https?:\/\/[\w\.-]+\.\w{2,}\/?[\w\~\-\.\?\,=\'\/\\\+&%\$#\(\)\;\:]*)(?<!\.)(?!["\'])/e',"smarty_function_external(array('href'=>\"\$1\",'text'=>'Link','nofollow'=>1,'title'=>\"\$1\"))",$posterText);

	$posterText = preg_replace('/(?<![\/F\.])(www\.[\w\.-]+\.\w{2,}\/?[\w\~\-\.\?\,=\'\/\\\+&%\$#\(\)\;\:]*)(?<!\.)(?!["\'])/e',"smarty_function_external(array('href'=>\"http://\$1\",'text'=>'Link','nofollow'=>1,'title'=>\"\$1\"))",$posterText);

	return $posterText;
}

function MakeLinks($posterText) {
	$posterText = preg_replace('/(?<!["\'>F=])(https?:\/\/[\w\.-]+\.\w{2,}\/?[\w\~\-\.\?\,=\'\/\\\+&%\$#\(\)\;\:]*)(?<!\.)(?!["\'])/e',"smarty_function_external(array('href'=>\"\$1\",'text'=>\"\$1\",'nofollow'=>1,'title'=>\"\$1\"))",$posterText);

	$posterText = preg_replace('/(?<![\/F\.])(www\.[\w\.-]+\.\w{2,}\/?[\w\~\-\.\?\,=\'\/\\\+&%\$#\(\)\;\:]*)(?<!\.)(?!["\'])/e',"smarty_function_external(array('href'=>\"http://\$1\",'text'=>\"\$1\",'nofollow'=>1,'title'=>\"\$1\"))",$posterText);

	$posterText = str_replace("/\n\n\n/",'<br/><br/>',$posterText);

	return $posterText;
}



function smarty_function_external($params)
{
	global $CONF;
  	//get params and use intelligent defaults...
  	$href=str_replace(' ','+',$params['href']);
  	if (strpos($href,'http://') !== 0)
  		$href ="http://$href";

  	if (isset($params['text']))
  		$text=$params['text'];
  	else
  		$text=$href;

  	if (isset($params['title']))
		$title=$params['title'];
	else
		$title=$text;
	
	if (isset($params['nofollow']))
		$title .= "\" rel=\"nofollow"; 	

  	if ($params['target'] == '_blank') {
  		return "<span class=\"nowrap\"><a title=\"$title\" href=\"$href\" target=\"_blank\">$text</a>".
  			"<img style=\"padding-left:2px;\" alt=\"External link\" title=\"External link - opens in a new window\" src=\"http://s0.geograph.org.uk/img/external.png\" width=\"10\" height=\"10\"/></span>";
  	} else {
  		return "<span class=\"nowrap\"><a title=\"$title\" href=\"$href\">$text</a>".
  			"<img style=\"padding-left:2px;\" alt=\"External link\" title=\"External link - shift click to open in new window\" src=\"http://s0.geograph.org.uk/img/external.png\" width=\"10\" height=\"10\"/></span>";
  	}
}
